package web_programing.udp.dictionary_service;

/**
 * udp
 * @author haomin
 * @date 2022/05/14 09:29
 **/

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Client2 {
    public static void main(String[] args) throws IOException {
        // 老陈的云服务器：
        // 目前服务器在本机: 182.254.132.183
        // 目前服务器的端口是: 8080

        // 目前只发送一次请求
        //String word = "apple";

        // 多次
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String word = scanner.nextLine();
            // 准备发送请求
            String request = "我是Java19班的\r\n" + word + "\r\n";

            byte[] bytes = request.getBytes("UTF-8");
            DatagramPacket sent = new DatagramPacket(
                    bytes,
                    0,
                    bytes.length,
                    // 老陈的云服务器
                    InetAddress.getByAddress(new byte[] {(byte)182, (byte)254, (byte)132, (byte)183}),
                    8080
            );
            DatagramSocket socket = new DatagramSocket(9999);
            socket.send(sent);

            // 接收方去接收数据
            byte[] buf = new byte[1024];
            DatagramPacket received = new DatagramPacket(buf, buf.length);

            socket.receive(received);       // 服务器会阻塞
            int n = received.getLength();
            String response = new String(buf, 0, n, "UTF-8");
            System.out.println(response);
        }
    }
}